package com.huxiu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.huxiu.holder.GroupInfoHolder;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.model.GroupInfo;
import com.huxiu.net.model.HuatiInfo;
import com.huxiu.net.model.QunZuList;
import com.huxiu.net.responses.BaseResponse;
import com.huxiu.net.responses.GroupInfoResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.ImageLoaderOptions;
import com.huxiu.utils.Settings;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.huxiu.view.RefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class QunZuDetailActivity extends BaseActivity {
    @ViewInject(R.id.big_header)
    private LinearLayout big_header;

    @ViewInject(R.id.bottom_bar_right)
    private LinearLayout bottom_bar_right;

    @ViewInject(R.id.small_header)
    private RelativeLayout small_header;

    @ViewInject(R.id.img_big)
    private ImageView img_big;

    @ViewInject(R.id.group_name)
    private TextView group_name;

    @ViewInject(R.id.text_chengyuannum)
    private TextView text_chengyuannum;

    @ViewInject(R.id.group_teamer)
    private TextView group_teamer;

    @ViewInject(R.id.text_content)
    private TextView text_content;


    @ViewInject(R.id.text_oper)
    private TextView text_oper;

    @ViewInject(R.id.shouqi)
    private ImageView shouqi;


    @ViewInject(R.id.img_group)
    private ImageView img_group;

    @ViewInject(R.id.text_group_name)
    private TextView text_group_name;

    @ViewInject(R.id.text_group_status)
    private TextView text_group_status;

    @ViewInject(R.id.zhankai)
    private ImageView zhankai;

    @ViewInject(R.id.lv_tabdetail_list)
    private RefreshListView lv_tabdetail_list;



    @ViewInject(R.id.layout_back)
    private RelativeLayout layout_back;

    @ViewInject(R.id.text_comment)
    private TextView text_comment;

    @ViewInject(R.id.layout_share)
    private RelativeLayout layout_share;

    @ViewInject(R.id.loading)
    private LinearLayout loading;// 加载中
    private String id;
    private int isJoin = -1;

    @ViewInject(R.id.text_jianjie)
    private TextView text_jianjie;

    private QunZuDetailActivity instance;

    public QunZuDetailActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_qunzu);
        ViewUtils.inject(this);
        instance=this;
        View top = View.inflate(this, R.layout.list_header_qunzu_detail, null);
        ViewUtils.inject(this, top);
        lv_tabdetail_list.addHeaderView(top);
        loading.setVisibility(View.VISIBLE);
        instance = this;
        initView();
        initData();
    }


    private void initView() {
        if (getIntent().hasExtra(Constants.GROUP_FINDGROUP_ITEM_KEY)) {
            String data = getIntent().getStringExtra(Constants.GROUP_FINDGROUP_ITEM_KEY);
            QunZuList.ForumRecomment mItem = new Gson().fromJson(data, QunZuList.ForumRecomment.class);
            id = mItem.id;
            isJoin = mItem.is_join;
        }

        if (getIntent().hasExtra(Constants.GROUP_MYGROUP_ITEM_KEY)) {
            String data = getIntent().getStringExtra(Constants.GROUP_MYGROUP_ITEM_KEY);
            QunZuList.ForumJoined mItem = new Gson().fromJson(data, QunZuList.ForumJoined.class);
            id = mItem.id;
            isJoin = 1;
        }
        if (getIntent().hasExtra(Constants.GROUP_HUTTI_ITEM_KEY)) {
            String data = getIntent().getStringExtra(Constants.GROUP_HUTTI_ITEM_KEY);
            HuatiInfo.Forum mItem = new Gson().fromJson(data, HuatiInfo.Forum.class);
            id = mItem.id;
            isJoin = mItem.is_join;
        }
        if (isJoin == 1) {
            big_header.setVisibility(View.GONE);
            small_header.setVisibility(View.VISIBLE);
        } else {
            big_header.setVisibility(View.VISIBLE);
            small_header.setVisibility(View.GONE);
        }
        // 给下拉刷新Listview设置监听器
        lv_tabdetail_list.setOnRefreshingListener(new MyOnRefreshingListener());
    }

    private void initData() {
        //注册广播接收者，并添加多个过滤器
        IntentFilter intent = new IntentFilter();
        intent.addAction(Constants.INTENT_HUATI_SUCCESS);
        intent.addAction(Constants.INTENT_QUNZU_JOIN_CHANGE);
        LocalBroadcastManager.getInstance(APP.getInstance()).registerReceiver(mReceiver, intent);
        if (!TextUtils.isEmpty(id)) {
            getDataFromServer();
        } else {
            Utils.showToast("请求不正确");
            return;
        }

    }

    //广播接收者
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constants.INTENT_HUATI_SUCCESS)) {
                if (!TextUtils.isEmpty(id)) {
                    getDataFromServer();
                } else {
                    Utils.showToast("请求不正确");
                    return;
                }
            } else if (action.equals(Constants.INTENT_QUNZU_JOIN_CHANGE)) {
                int is_join_num = intent.getIntExtra("is_join_status", 4);
                isJoin = is_join_num;
                if (is_join_num == 1) {
                    text_group_status.setText("已加入");
                    text_oper.setText("退出群组");
                    text_oper.setBackgroundResource(R.drawable.juxing_bg_gry);
                    text_jianjie.setVisibility(View.GONE);
                    text_oper.setTextColor(getResources().getColor(R.color.gray5));
                } else {
                    text_group_status.setText("未加入");
                    text_oper.setText("加入群组");
                    text_oper.setBackgroundResource(R.drawable.juxing_bg_blue);
                    text_jianjie.setVisibility(View.VISIBLE);
                    text_oper.setTextColor(getResources().getColor(R.color.white));
                }
            }
        }
    };

    @OnClick({R.id.zhankai, R.id.shouqi, R.id.layout_back, R.id.text_comment, R.id.layout_share, R.id.text_oper})
    public void monClick(View v) {
        switch (v.getId()) {
            case R.id.zhankai:
                UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_LIST, UmenEvent.TOPIC_LIST_OPEN_SHARE);
                big_header.setVisibility(View.VISIBLE);
                small_header.setVisibility(View.GONE);
                break;
            case R.id.shouqi:
                big_header.setVisibility(View.GONE);
                small_header.setVisibility(View.VISIBLE);
                break;
            case R.id.layout_back:
                instance.finish();
                break;
            case R.id.text_comment:
                if (!Settings.isLoggedIn()) {
                    Utils.askLogIn(instance);
                    return;
                }
                if (!(isJoin == 1)) {
                    Utils.showToast("您还未加入该小组");
                    return;
                }

                Intent intent = new Intent(this, SubmitHuatiActivity.class);
                intent.putExtra(Constants.GROUP_GROUP_ITEM_ID, mGroupInfo.forum.id);
                startActivity(intent);
                break;
            case R.id.layout_share:

                new AsyncTask<Void, Void, Void>() {
                    Bitmap bmp = null;

                    @Override
                    protected Void doInBackground(Void... params) {
                        bmp = ImageLoader.getInstance().loadImageSync(mGroupInfo.forum.pic_path + Constants.IMAGE_WEBP);
                        //                        bmp = ImageLoader.getInstance().loadImageSync("https://gd2.alicdn.com/bao/uploaded/i2/TB1uH32KpXXXXcqXFXXXXXXXXXX_!!0-item_pic.jpg");
                        return null;
                    }
                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        Utils.launchShareActivity(instance,
                                mGroupInfo.forum.name, mGroupInfo.forum.share_url, "doc", mGroupInfo.forum.pic_path,
                                mGroupInfo.forum.desc, bmp, UmenEvent.GROUP_SHARE);
                    }
                }.execute();
                break;
            case R.id.text_oper:
                if (!Settings.isLoggedIn()) {
                    Utils.askLogIn(instance);
                    return;
                }
                operGroup();
                break;
        }
    }

    private void operGroup() {

        String url = (mGroupInfo.forum.is_join == 1 ? NetworkConstants.FORUM_QUIT : NetworkConstants
                .FORUM_JOIN);

        Map<String, String> params = new LinkedHashMap<>();

        params.put("id", mGroupInfo.forum.id + "");

        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    Utils.showToast("操作成功");
                    int status = (mGroupInfo.forum.is_join == 1 ? 0 : 1);
                    if(status==1){
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_LIST, UmenEvent.TOPIC_LIST_JOIN);
                    }else{
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_LIST, UmenEvent.TOPIC_LIST_OUT);
                    }
                    mGroupInfo.forum.is_join = status;
                    isJoin = status;
                    Intent data = new Intent();
                    data.putExtra("is_join_num", status);
                    setResult(RESULT_OK, data);

                    //发送广播
                    Intent intent = new Intent(Constants.INTENT_QUNZU_JOIN_CHANGE);
                    intent.putExtra("is_join_status", status);
                    LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                    data();
                } else {
                    Log.e("webviewui", "失败");
                    Utils.showToast(response.error.message);
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(error.getMessage());
            }
        });
        BaseActivity.getmQueue().add(request);
        //        mQueue.start();
    }


    private boolean isRefresh = false;// 当前是否是下拉刷新

    private boolean isLoadMore = false;// 当前是否是加载更多


    class MyOnRefreshingListener implements RefreshListView.OnRefreshingListener {
        @Override
        public void onRefreshing() {
            isRefresh = true;
            // 下拉刷新业务
            getDataFromServer();
        }

        @Override
        public void onLoadingMore() {
            if (currentPage < totalPages) {
                isLoadMore = true;
                // 加载更多业务
                getMoreDataFromServer();
            } else {
                lv_tabdetail_list.loadMoreFinished();
                //                Utils.showToast(R.string.no_more);
                Toast.makeText(QunZuDetailActivity.this, R.string.no_more, Toast.LENGTH_SHORT).show();
            }
        }

    }

    //下拉刷新
    private void getDataFromServer() {
        loadList(0);
    }

    //上拉加载
    private void getMoreDataFromServer() {
        loadList(currentPage + 1);
    }


    private int totalPages = 0;
    private int currentPage = 0;
    private List<GroupInfo.Thread> lists = new ArrayList<>();
    private GroupInfo mGroupInfo;

    //获取推荐页列表页数据
    private void loadList(final int page) {
        String url = NetworkConstants.FORUM;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("id", id);
        GsonRequest<GroupInfoResponse> request = new GsonRequest<>(url, Request.Method.POST,
                GroupInfoResponse.class, true, params,
                new Response.Listener<GroupInfoResponse>() {
                    @Override
                    public void onResponse(GroupInfoResponse response) {
                        if (response.isSuccess()) {
                            loading.setVisibility(View.INVISIBLE);
                            bottom_bar_right.setVisibility(View.VISIBLE);
                            if (page == 0) {
                                lists.clear();
                            }
                            mGroupInfo = response.data;
                            data();
                            Collections.addAll(lists, response.data.thread);
                            currentPage = response.data.cur_page;
                            totalPages = response.data.total_page;
                            parseListJson(lists);
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                lv_tabdetail_list.refreshFinished(true);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                lv_tabdetail_list.loadMoreFinished();
                                isLoadMore = false;

                            }
                        } else {
                            Utils.showToast(response.error.message);
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                lv_tabdetail_list.refreshFinished(false);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                lv_tabdetail_list.loadMoreFinished();
                                isLoadMore = false;
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(R.string.generic_failure);
                // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                if (isRefresh) {
                    lv_tabdetail_list.refreshFinished(false);
                    isRefresh = false;
                } else if (isLoadMore) {
                    lv_tabdetail_list.loadMoreFinished();
                    isLoadMore = false;
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }

    private void data() {
        group_name.setText(mGroupInfo.forum.name);
        text_group_name.setText(mGroupInfo.forum.name);
        ImageLoader.getInstance().displayImage(
                mGroupInfo.forum.pic_path + Constants.IMAGE_WEBP, img_group, ImageLoaderOptions.options);
        ImageLoader.getInstance().displayImage(
                mGroupInfo.forum.pic_path + Constants.IMAGE_WEBP, img_big, ImageLoaderOptions.options);

        text_chengyuannum.setText(mGroupInfo.forum.user_total + "成员");
        group_teamer.setText("组长：" + mGroupInfo.forum.master.username);
        text_content.setText(mGroupInfo.forum.desc);
        if (mGroupInfo.forum.is_join == 1) {
            text_group_status.setText("已加入");
            text_oper.setText("退出群组");
            text_oper.setBackgroundResource(R.drawable.juxing_bg_gry);
            text_jianjie.setVisibility(View.GONE);
            text_oper.setTextColor(getResources().getColor(R.color.gray5));
        } else if (mGroupInfo.forum.is_join == 0) {
            text_group_status.setText("未加入");
            text_oper.setText("加入群组");
            text_oper.setBackgroundResource(R.drawable.juxing_bg_blue);
            text_jianjie.setVisibility(View.VISIBLE);
            text_oper.setTextColor(getResources().getColor(R.color.white));
        }

    }


    private void parseListJson(List<GroupInfo.Thread> lists) {
        if (!isLoadMore) {
            adapter = new SpareAdapter();
            lv_tabdetail_list.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }


    SpareAdapter adapter;

    private class SpareAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public Object getItem(int position) {
            return lists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            GroupInfoHolder holder;
            View view = convertView;
            if (view == null) {
                view = View.inflate(instance, R.layout.item_group_list, null);
                holder = new GroupInfoHolder(view, instance);
                view.setTag(holder);
            }
            holder = (GroupInfoHolder) view.getTag();
            GroupInfo.Thread item = lists.get(position);
            holder.setAdapter(adapter);
            holder.bindItem(item);//这里用来把获取到的数据传递给holder
            return view;
        }
    }



    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }


}
